package org.nokatag.password;

import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.nokatag.system.BugInfoWrint;

public class HmacPass {
	
	/**
	 * 加密
	 * @param keys
	 * @param asc
	 * @return
	 */
	public static PassStr Pass(byte[] keys,String ... asc){
		String[] praves = ArrayFormat(asc);
		PassStr passStr=new PassStr();
		
		byte[] keyBytes = keys;//密钥
		Random  rand=new Random();
        byte[ ] salt=new byte[12];
        rand.nextBytes(salt);
        
		SecretKey key = new SecretKeySpec(keyBytes, praves[1]);//加密
		try {
			/**
			 * 生成Mac对象其中传入的参数指定计算消息验证码所使用的算法，常用的有"HmacMD5"和"HmacSHA1"等
			 */
			Mac m = Mac.getInstance(praves[2]);
			m.init(key);
			m.update(praves[0].getBytes());
			m.update(salt);
			byte[] mac = m.doFinal();
			
			String password = Msg.toHexString(mac);
			
			 passStr.setPass(password);
			 passStr.setSalt(salt);
			 passStr.setSrcpass(praves[0]);

		} catch (Exception se) {
			BugInfoWrint.Print(se);
		}
		
		return passStr;
	}
	
	/**
	 * 解密比较
	 * @param keys
	 * @param asc
	 * @return
	 */
	public static boolean ePass(byte[] keys,byte[] saltst,String pass,String ... asc){
		String[] praves = ArrayFormat(asc);
		
		byte[] keyBytes = keys;//密钥
        byte[ ] salt=saltst;//绕码
        
		SecretKey key = new SecretKeySpec(keyBytes, praves[1]);//加密
		try {
			/**
			 * 生成Mac对象其中传入的参数指定计算消息验证码所使用的算法，常用的有"HmacMD5"和"HmacSHA1"等
			 */
			Mac m = Mac.getInstance(praves[2]);
			m.init(key);
			m.update(praves[0].getBytes());
			m.update(salt);
			byte[] mac = m.doFinal();
			
			String password = Msg.toHexString(mac);
			if(password.equals(pass)){
				return true;
			}else{
				return false;
			}
		} catch (Exception se) {
			BugInfoWrint.Print(se);
		}
		
		return false;
	}
	//----------------------------------------------
	private static String[] ArrayFormat(String[] args){
		Integer longarr = args.length;
		String[] prave = new String[3];
		switch (longarr) {
		case 0:
			prave[0]="pass";
			prave[1]="HMACSHA3";
			prave[2]="HmacMD5";
			break;
		case 1:
			prave[0]=args[0];
			prave[1]="HMACSHA3";
			prave[2]="HmacMD5";
			break;
		case 2:
			prave[0]=args[0];
			prave[1]=args[1];
			prave[2]="HmacMD5";
			break;
		case 3:
			prave[0]=args[0];
			prave[1]=args[1];
			prave[2]=args[2];
			break;
		default:
			prave[0]="pass";
			prave[1]="HMACSHA3";
			prave[2]="HmacMD5";
			break;
		}
		return prave;
	}

}
